import { Vec3 } from "cc";

class MoveTarget {
    private _targetLeftSecond = 0;
    private _targetUnit = Vec3.ZERO.clone();
    private _realOffset = Vec3.ZERO.clone();
    private _started = false;

    constructor(public moveOffset: Vec3, public targetSecond: number, public endEvent?: Function) {
        this._realOffset = this.moveOffset.clone();
    }

    start() {
        this._targetUnit = new Vec3(this.moveOffset.x / this.targetSecond, this.moveOffset.y / this.targetSecond, this.moveOffset.z / this.targetSecond);
        this._targetLeftSecond = this.targetSecond;
        this._realOffset = Vec3.ZERO.clone();
        this._started = true;
    }

    update(deltaTime: number) {
        if (this._targetLeftSecond > 0) {
            const offset = this._targetUnit.clone().multiplyScalar(Math.min(deltaTime, this._targetLeftSecond));
            this._targetLeftSecond -= deltaTime;
            this._realOffset.add(offset);
            return offset;
        }
        const offset = this.moveOffset.clone().subtract(this._realOffset);
        if (offset.length() != 0) {
            this._realOffset = this.moveOffset;
            return offset;
        }

        if (this._started) {
            this._started = false;
            if (typeof this.endEvent === 'function') {
                this.endEvent();
            }
        }

        return 0
    }

    get isRunning() {
        return this._targetLeftSecond > 0;
    }
}

export { MoveTarget };
